//路由 router
const express = require('express');
const path = require('path')
const fs = require('fs')
const mysql = require('mysql')
const router = express.Router();
const multer = require('multer')
const dbQuery = require('../model/query.js')
const CateController = require('../controller/CateController.js');
// console.log(path.join(__dirname));//C:\Users\86136\Desktop\全栈历练练习\7.30
// console.log(path.join(__dirname,'../uploads'));//C:\Users\86136\Desktop\全栈历练练习\7.30\router

const { getUnixTime } = require('../util/tool.js')
//设置上传的目录
const upload = multer({ dest: (path.join(__dirname, '../uploads')) })

// 连接数据库
let dbConfig = require('../config/dbconfig.js')
const connection = mysql.createConnection(dbConfig);

//连接mysql1
connection.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log('成功射死');
});

//导入控制器模块
const ArticleController = require('../controller/ArticleController.js')
const UserController = require('../controller/UserController.js');
const { json } = require('express');
const { parse } = require('path');
const { insert } = require('../controller/ArticleController.js');

//后台首页
router.get('/', (req, res) => {
    let userInfo = JSON.parse(req.session.userInfo || '{}');
    res.render('index.html', { userInfo })
})

// 文章列表
router.get('/article', ArticleController.index)
// 文章回收站列表
router.get('/recyclelist', ArticleController.recyclelist)
// 文章删除
router.get('/delete', ArticleController.delete)
// 添加文章的表单页面
router.get('/add', ArticleController.add)
// 实现数据添加入库
router.post('/insert', upload.single('img'), ArticleController.insert)
//实现编辑文章的回显操作
router.get('/edit', ArticleController.edit)
//实现文章更新入库操作
router.post('/update', upload.single('img'), ArticleController.update)
//实现文章加入回收站
router.get('/recycle', ArticleController.recycle)
//实现文章还原
router.get('/restore', ArticleController.restore)
//更改标题logo
router.get('/systemData', UserController.systemData)
router.post('/updsystemData', upload.single('blogLogo'), UserController.updsystemData)
//处理单文件上传
router.post('/upload', upload.single('photo'), ArticleController.upload)
//更新头像  
router.post('/uploadAvatar', upload.single('avater'), (req, res) => {
    console.log(req.file);//接收二进制文件
    let { originalname, filename, destination } = req.file
    let ext = originalname.substring(originalname.indexOf('.'));
    //把上传成功后的文件进行重命名
    let oldPath = path.join(__dirname, '../', 'uploads', filename);
    let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;
    fs.renameSync(oldPath, newPath)
    //把上传成功的图片路径更行到用户表
    let userInfo = JSON.parse(req.session.userInfo);
    let { user_id } = userInfo;//获取当前所登录用户
    console.log('userInfo', req.session.userInfo);
    let avater = 'uploads/' + filename + ext;
    let sql = `update users set avater = '${avater}'where user_id = ${user_id}`
    dbQuery(sql).then(result => {
        // a
        userInfo.avater = avater;
        // 再存入到session中去
        req.session.userInfo = JSON.stringify(userInfo)
        if (result.affectedRows) {
            res.json({
                code: 20000,
                message: "头像更换成功",
                src: avater
            })
        } else {
            res.json({
                code: -2000,
                message: "头像更换失败",
            })
        }


    })
})
//用户登录
router.get('/login', UserController.login)
//展示用户注册的页面
router.get('/register', UserController.register)
//处理用户登录逻辑
// router.post('/dologin', UserController.dologin)
//处理用户退出逻辑
router.get('/logout', UserController.logout)
//ajax登录
router.post('/ajaxlogin', UserController.ajaxlogin)

// 用户注册入库
router.post('/ajaxregister', UserController.ajaxregister)

// 校验邮箱是否占用
router.post('/ajaxemail', UserController.ajaxemail)

//ajax文章删除
router.post('/ajaxdelete', ArticleController.ajaxdelete)

// 更新用户的密码
router.post('/updatePassword', UserController.updatePassword)


// 分类列表模板展示
router.get('/catelist', CateController.list)

// 获取分类数据的api接口
router.get("/getCateData", CateController.cate)

// 展示编辑分类的页面
router.get('/editCate', CateController.edit)

// 获取当前指定的分类
router.get('/getCateDetail', CateController.detail)

// 删除分类
router.post("/deleteCate", CateController.delete)

//添加分类
router.get('/addCate', CateController.addCate)

//添加分类api接口
router.post('/ajaxAddCate', upload.single(''), CateController.insertCate)

// 更新分类
router.post('/updateCate', CateController.updateCate)

// 给文章添加内容展示视图

router.get('/editContent', ArticleController.editContent)

router.post('/updateArtilceContent', ArticleController.updateArtilceContent)

// 文章分页数据
router.get('/articleCount', ArticleController.articleCount)

router.get('/cateArticleCount', ArticleController.cateArticleCount)

//获取分类页面的文章
router.get('/cateList', async (req, res) => {
    let { page = 1, pagesize = 2, cat_id } = req.query;
    let offset = (page - 1) * pagesize;
    let sql = `select t1.*, t2.name from mypost t1 left join mycategories t2 on t1.cat_id = t2.id where t1.cat_id = ${cat_id} 
             and t1.is_delete = 0 and t1.state=1 limit ${offset},${pagesize}`
    let result = await myQueryPromise(sql)
    res.json(result)
})

//导出模块
module.exports = router;
